// 定义一个蛇的类
class Snake {
    // 蛇
    snakeElement: HTMLElement;
    // 定义一个蛇头
    snakeHead: HTMLElement;
    // 定义身体，包括头
    bodys: HTMLCollection;
    constructor() {
        this.snakeElement = document.getElementById('snake')!;
        this.snakeHead = document.querySelector('#snake>div')!;
        this.bodys = document.getElementById('snake')!.getElementsByTagName('div');

    }
    // 蛇头的X轴坐标
    get X() {
        return this.snakeHead.offsetLeft;
    }
    // 蛇头的Y轴坐标
    get Y() {
        return this.snakeHead.offsetTop;
    }
    //设置蛇头X轴坐标，蛇水平移动
    set X(val: number) {
        // 如果新值跟旧值相等就不再修改
        if (this.X === val) {
            return;
        }
        // 检查是否撞墙
        if (val < 0 || val > 290) {
            throw new Error('蛇撞墙了')
        }
        // 检测是否撞掉头
        if (this.bodys[1] && (this.bodys[1] as HTMLElement).offsetLeft == val) {
            console.log('水平方向发生掉头');
            // 向右掉头
            if (val > this.X) {
                val = this.X - 10;
            } else {
                // 向左掉头
                val = this.X + 10;
            }
        }
        // 使蛇身移动
        this.moveBody();
        this.snakeHead.style.left = val + 'px'
        // 判断蛇头是否撞到身体
        this.checkHeadBody();

    }
    //设置蛇头Y轴坐标，蛇垂直移动
    set Y(val: number) {
        // 如果新值跟旧值相等就不再修改
        if (this.Y === val) {
            return;
        }
        // 检查是否撞墙
        if (val < 0 || val > 290) {
            throw new Error('蛇撞墙了')
        }
        // 检测是否撞掉头
        if (this.bodys[1] && (this.bodys[1] as HTMLElement).offsetTop == val) {
            console.log('垂直方向发生掉头');
            // 向下掉头
            if (val > this.Y) {
                val = this.Y - 10;
            } else {
                // 向上掉头
                val = this.Y + 10;
            }
        }
        // 使蛇身移动
        this.moveBody();
        this.snakeHead.style.top = val + 'px'
        // 判断蛇头是否撞到身体
        this.checkHeadBody();
    }
    //增加蛇的身体
    addBodys() {
        this.snakeElement.insertAdjacentHTML('beforeend', '<div></div>');
    }
    // 使身体移动
    moveBody() {
        for (let i = this.bodys.length - 1; i > 0; i--) {
            (this.bodys[i] as HTMLElement).style.left = (this.bodys[i - 1] as HTMLElement).offsetLeft + 'px';
            (this.bodys[i] as HTMLElement).style.top = (this.bodys[i - 1] as HTMLElement).offsetTop + 'px';
        }
    }
    checkHeadBody() {
        for (let i = 1; i < this.bodys.length; i++) {
            const X = (this.bodys[i] as HTMLElement).offsetLeft;
            const Y = (this.bodys[i] as HTMLElement).offsetTop;;
            if (this.X == X && this.Y == Y) {
                throw new Error('蛇撞身体了！')
            }
        }
    }
}
export default Snake;